package com.education.admin.api.controller;

import com.education.common.annotation.Param;
import com.education.common.annotation.ParamsType;
import com.education.common.annotation.ParamsValidate;
import com.education.common.base.BaseController;
import com.education.common.constants.Constants;
import com.education.common.model.AdminUserSession;
import com.education.common.model.JwtToken;
import com.education.common.model.OnlineUser;
import com.education.common.model.OnlineUserManager;
import com.education.common.utils.IpUtils;
import com.education.common.utils.Result;
import com.education.common.utils.ResultCode;
import com.education.service.system.SystemAdminService;
import com.education.service.task.LoginSuccessListener;
import com.education.service.task.TaskManager;
import com.education.service.task.TaskParam;
import com.education.service.websocket.SystemWebSocketHandler;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 余一
 * @Description 登录controller
 * @date 2021/7/1 11:33
 */
@RestController
public class LoginController extends BaseController {
    @Resource
    private SystemAdminService systemAdminService;
    @Resource
    private JwtToken jwtToken;
    @Resource
    private TaskManager taskManager;
    @Resource
    private OnlineUserManager onlineUserManager;
    @Autowired
    private SystemWebSocketHandler systemWebSocketHandler;

    @PostMapping("/login")
    @ParamsValidate(params = {
            @Param(name = "userName", message = "请输入用户名"),
            @Param(name = "password", message = "请输入密码"),
            @Param(name = "key", message = "请传递一个验证码时间戳"),
            @Param(name = "imageCode", message = "请输入验证码"),
    }, paramsType = ParamsType.JSON_DATA)
    public Result login(HttpServletRequest request, @RequestBody Map params){
       String key = String.valueOf(params.get("key"));
       String username = (String) params.get("userName");
       String password = (String) params.get("password");
       String imageCode = (String) params.get("imageCode");
       String cacheCode = redisCacheBean.get(key);
//       String cacheCode = (String) redisTemplate.opsForValue().get(key);
       if (!imageCode.equalsIgnoreCase(cacheCode)){
           return Result.fail(ResultCode.FAIL,"验证码输入错误！");
       }
       Result result = systemAdminService.login(username, password);

       if (result.isSuccess()) {
            //加载用户角色菜单权限信息
           AdminUserSession userSession = systemAdminService.getAdminUserSession();
           Integer userId = (Integer) userSession.getUserMap().get("id");
           //检查该用户是否在其他设备上登录
           systemAdminService.checkOnlineUser(userId);
           //将当前登录用户添加到用户容器
           String sessionId = request.getSession().getId();
           OnlineUser onlineUser = new OnlineUser(sessionId, userSession);
           onlineUserManager.addOnlineUser(userId,onlineUser);
           //加载用户的菜单和权限
           systemAdminService.loadUserMenuAndPermission(userSession);
           params.clear();
           //创建一个token
           String token = jwtToken.createToken(userSession.getUserMap().get("id"), Constants.FIVE_DAY_TIMEOUT);
           params.put("token",token);
           HashMap userInfo = new HashMap<>();
           userInfo.put("id",userSession.getUserMap().get("id"));
           userInfo.put("menuList",userSession.getMenuList());
           userInfo.put("permissionList",userSession.getPermissionList());
           userInfo.put("login_name",userSession.getUserMap().get("login_name"));
           params.put("userInfo",userInfo);


           //更新用户登录信息
           TaskParam taskParam = new TaskParam(LoginSuccessListener.class);
           //获取之前用户的登录次数
           Integer loginCount= (Integer) userSession.getUserMap().get("login_count");
           taskParam.put("login_count",++loginCount);
           taskParam.put("login_ip", IpUtils.getAddressIp(request));
           taskParam.put("last_login_time",new Date());
           taskParam.put("id",userSession.getUserMap().get("id"));
           taskManager.pushTask(taskParam);
           result.setData(params);
       }
       return result;
    }

    @PostMapping("/logout")
    public Result logout(HttpServletRequest request){
        String sessionId = request.getSession().getId();
        systemWebSocketHandler.clearWebSocketSession(sessionId);

        Integer userId = (Integer) systemAdminService.getAdminUserSession().getUserMap().get("id");
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        //清除在线用户
        onlineUserManager.removeOnlineUser(userId);
        return Result.success(ResultCode.SUCCESS,"退出成功");
    }

    @GetMapping("/unAuth")
    public Result unAuth(){
        return Result.fail(ResultCode.NOT_AUTH,"用户未认证");
    }
}
